package org.csu.mypetstore.controller.user;

import org.csu.mypetstore.common.CommonResponse;
import org.csu.mypetstore.domain.BO.OrderBO;
import org.csu.mypetstore.domain.BO.OrderListInfo;
import org.csu.mypetstore.domain.PO.LineItem;
import org.csu.mypetstore.domain.PO.Order;
import org.csu.mypetstore.service.CartItemService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.List;

@Controller
@CrossOrigin(origins = "*",allowCredentials="true",allowedHeaders = "",methods = {})
@SessionAttributes(value = {"cartItemList", "admin", "order","orderList","lineItemList","adminOrderList","account","msg"})
public class OrderController {

    private static SimpleDateFormat sdf = new SimpleDateFormat("MM-yyyy");
    @Autowired
    private OrderService orderService;

    @GetMapping("/account/{username}/orders")
    @ResponseBody
    public CommonResponse<List<OrderListInfo>> viewOrder(@PathVariable("username") String username) {
        List<OrderListInfo> list = orderService.getOrdersByUsername(username);
        if(list == null)
            return CommonResponse.createForError("订单列表为空");
        return CommonResponse.createForSuccess(list, "成功");
    }

    @GetMapping("/Orders/{orderId}")
    @ResponseBody
    public CommonResponse<OrderBO> viewOrderByOrderId(@PathVariable("orderId") String orderId) {
        OrderBO orderBO = orderService.getOrderBO(Integer.parseInt(orderId));//通过orderId查询该订单
        return CommonResponse.createForSuccess(orderBO, "成功");
    }

    @PostMapping("/account/{username}/orders")
    @ResponseBody
    public CommonResponse<String> comfirm(@PathVariable("username") String username, OrderBO orderBO){
//        //TODO 用户上传的order价格可能是假的
        orderService.insertOrder(orderBO);//插入order并更新库存
        //获取用户信息并清空该用户的购物车
//        cartItemService.removeAllCartItem(accountVO.getAccount().getUsername());//清空购物车
        return CommonResponse.createForSuccessMessage("新建订单成功");
    }
}
